package com.netease.cloud.cm.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Random;

public class CommonStringUtils {

    private static Properties properties;

    public static String getConfig(String descKey) {
        String pattern = null;
        InputStream is = null;
        if (properties != null) {
            String r = properties.getProperty(descKey);
            if (r == null) {
                return "";
            }
            return r.trim();
        }
        synchronized(CommonStringUtils.class) {
            try {
                String str = new GetEnvConfig().getEnvConfig();
                properties = new Properties();
                is = new FileInputStream(str);
                properties.load(is);
                String r = properties.getProperty(descKey);
                if (r == null) {
                    return "";
                }
                pattern = r.trim();
            } catch (IOException e) {
                properties = null;
                e.printStackTrace();
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return pattern;
    }

    public static String getBaseUrl() {
        return getConfig("ncm.server.address");
    }

    public static String getAlarmUrl() {
        return getConfig("alarm.address");
    }

    public static String getRandomString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public static int getRandomInt(int min, int max) {
        Random random = new Random();
        return random.nextInt(max) % (max - min + 1) + min;
    }
}
